﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Certs
{
    class CertGenerator
    {
        public static string GenerateCert(string host)
        {
            if (!Uri.CheckSchemeName(host))
                return null;

            string generaredsPath   = string.Concat(Configuration.Complementary.path, "Certs\\Generated\\");
            string outFileCert      = string.Concat(generaredsPath, host, ".cer");
            string caCer            = string.Concat(Configuration.Complementary.path, "Certs\\ProxyMe.cer");
            string caPvk            = string.Concat(Configuration.Complementary.path, "Certs\\ProxyMe.pvk");
            string makecert         = string.Concat(Configuration.Complementary.path,"Certs\\makecert.exe");
            

            if (!System.IO.Directory.Exists(generaredsPath))
                System.IO.Directory.CreateDirectory(generaredsPath);
            if (System.IO.File.Exists(outFileCert))
                return outFileCert;

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = new System.Diagnostics.ProcessStartInfo(makecert, @"-n ""CN=" + host + @"""  -ic """ + caCer + @""" -iv """ + caPvk + @""" -a sha1  -sky exchange -pe -sr currentuser -ss my """ + outFileCert + @"""");
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.Start();
            proc.WaitForExit();

            return outFileCert;
        }
    }
}
